package com.alvin.abp.web.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alvin.abp.domain.AlvinUser;
import com.alvin.abp.domain.Gender;
import com.alvin.abp.domain.editor.DateEditor;
import com.alvin.abp.domain.validator.UserValidator;
import com.alvin.abp.service.UserService;
/**   
 * 
 * @author <a href="mailto:rex2.mj@gmail.com">Leo Meng</a>
 * @date $Date: Mar 25, 2013 $
 */
@Controller
public class UserAdminController {
	@Autowired
	private UserService userService;
	protected final Log logger = LogFactory.getLog(getClass());
	@Autowired
	@Qualifier("org.springframework.security.authenticationManager")
    protected AuthenticationManager authenticationManager;	
	
	@Autowired
	private UserValidator userValidator;
	
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateEditor());
    }
	
	@RequestMapping(value = "/reg.htm", method = RequestMethod.GET)
	public String regForm(ModelMap model) {
		AlvinUser user = new AlvinUser();
		Gender[] genders = Gender.values();
		model.addAttribute("genders", genders);
		model.addAttribute("user", user);
		return "user/reg";
	}

	@RequestMapping(value = "/reg.htm", method = RequestMethod.POST)
	@Transactional
	public String reg(@ModelAttribute("user") AlvinUser user, Errors errors,
			ModelMap model, HttpServletRequest request) throws ServletException, IOException {

		ValidationUtils.invokeValidator(userValidator, user, errors);

		String view = "user/reg";

		if (!errors.hasErrors()) {
			try {
				userService.addUser(user);
//				UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
//				
//				token.setDetails(new WebAuthenticationDetails(request));
//		        Authentication authenticatedUser = authenticationManager.authenticate(token);
//
//		        SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
//		        request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());				
				view = "redirect:/home.htm";
			} catch(AuthenticationException ex) {
				return "user/reg";
			} catch (DataAccessException ex) {
				errors.rejectValue("mobile","error.user.mobile.exists",new Object[]{user.getMobile()},"");
			}
		}

		if (errors.hasErrors()) {
			model.addAttribute("user", user);
			Gender[] genders = Gender.values();
			model.addAttribute("genders", genders);
			model.addAllAttributes(errors.getAllErrors());
		}

		return view;

	}
	
}
